<?php

global $lang;
include_once ('bn_path.php');

class column
{
    public $caption = '';
    public $field_name = '';
    public $css_class = '';
    public $readonly = false;
    public $hide = false;
    public $template = '';
    public $function = '';
    public $editable = '';
}

class gridbtn
{
    public $caption = '';
    public $enable = false;
    public $cssclass = '';
}

class bn_grid
{
    public $name = 'grid1';
    public $page_size = 10;
    public $paging;
    public $delete;
    public $update;
    public $select;
    public $header;
    public $border = 1;
    public $cssclass_Table = '';
    public $cssclass_TR = '';
    public $cssclass_footer='';
    public $columns;
    public $div = '#show';
    public $recivepage;
    public $select_jquery='';
    public $select_color = '';
    public $delete_msg = 'do our want delete this row?';

    protected static $instance;

    public function __construct()
    {
        $this->columns = new ArrayObject();
        $this->paging = new gridbtn;
        $this->delete = new gridbtn;
        $this->update = new gridbtn;
        $this->select = new gridbtn;
        $this->header = new gridbtn;
    }

    public static function getInstance()
    {
        if (!isset(self::$instance))
        self::$instance = new self();
        return self::$instance;
    }

    private function header()
    {
        if($this->header->cssclass!='')
        $this->header->cssclass=" class='$this->header->cssclass'";
        
        $grid = "\t<thead".$this->header->cssclass.">\n<tr>\n";
        if ($this->header->caption != '')
        {
            $header=explode(',',$this->header->caption);
            foreach($header as $h)
            {
             $grid .= "\t<th>$h</th>\n";   
            }
        } 
        else
        {
            foreach ($this->columns as $col)
            {
                $hide = '';
                if ($col->hide)
                    $hide = ' style="display:none;"';
                $grid .= "\t<th" . $hide . ">" . $col->caption . "</th>\n";
            }
        }
        return $grid . "\n</tr>\n</thead>\n";
    }

    private function paging($page, $pag)
    {
        $btn = explode(',', $this->paging->caption);
        if($this->paging->cssclass!='')
        $this->paging->cssclass = ' class="'.$this->paging->cssclass.'"';
        if ($page == 0)
        {
            $grid .= "<input type='submit' value='{$btn[0]}' name='pageing'".$this->paging->cssclass." disabled>\n";
            $grid .= "<input type='submit' value='{$btn[1]}' name='pageing'".$this->paging->cssclass." disabled>\n";
        } else
        {
            $grid .= "<input type='submit' value='{$btn[0]}' name='pageing'".$this->paging->cssclass." data-pnumber='0'>\n";
            $grid .= "<input type='submit' value='{$btn[1]}' name='pageing'".$this->paging->cssclass." data-pnumber='" . ($page -1) . "'>\n";
        }
        if ($pag == $page || ($page == 0 && $pag == 0))
        {
            $grid .= "<input type='submit' value='{$btn[2]}' name='pageing'".$this->paging->cssclass." disabled>\n";
            $grid .= "<input type='submit' value='{$btn[3]}' name='pageing'".$this->paging->cssclass." disabled>\n";
        } else
        {
            $grid .= "<input type='submit' value='{$btn[2]}' name='pageing'".$this->paging->cssclass." data-pnumber='" . ($page +1) . "'>\n";
            $grid .= "<input type='submit' value='{$btn[3]}' name='pageing'".$this->paging->cssclass." data-pnumber='" . ($pag) ."'>\n";
        }
        return $grid . "<input type='hidden' name='" . $this->name . "_page' id='" . $this->name . "_page' value='$page'/>\n";
    }

    public function Get_field_list($col)
    {
        preg_match_all('/<%(.*?)%>/', $col->template, $matches);
        return $matches[1];
    }

    public function show($datasource, $page = 0)
    {
        $grid = '';
        //create columns
        if (!empty($datasource))
        {//_______________________________css tyle____________________________________
            if ($this->cssclass_Table != '')
                $this->cssclass_Table = " class='$this->cssclass_Table'";
            if ($this->cssclass_TR != '')
                $this->cssclass_TR = " class='$this->cssclass_TR'";
            if ($this->cssclass_delete != '')
                $this->cssclass_delete = " class='$this->cssclass_delete'";
            if ($this->cssclass_update != '')
                $this->cssclass_update = " class='$this->cssclass_update'";
            //______________________________________create column______________________________________________________
            if ($this->columns->count()==0)
            {
                $row=$datasource[0];
                if(is_object($row))
                $row=(array)$row;
                $keys=array_keys($row);
                foreach($keys as $key)
                {
                   $col=new column;
                   $col->field_name=$key;
                   $col->caption=$key;
                   $this->columns->append($col); 
                }
            }//______________________________________begin table_____________________________________________________
                if ($this->border != '')
                    $this->border = " border='$this->border'";
                if ($this->name != '')
                    $name = " name='$this->name' id='$this->name'";
                $grid = "\n<table$name$this->border$this->cssclass_Table>\n";
                //________________________________generate head grid_________________________________________________
                if($this->header->enable)
                $grid .=self::header();
                //_________________________________genrate footer grid_______________________________________________
                if ($this->cssclass_footer != '')
                $this->cssclass_footer = " class='$this->cssclass_footer'";
                $grid.="<tfoot$this->cssclass_footer>\n<tr>\n<td colspan='".$this->columns->count()."'>";
                if ($this->paging->enable)
                {
                    $j = count($datasource);
                    $pag = intval($j / $this->page_size);
                    $rem = $j % $this->page_size;
                    if ($rem == 0)
                        --$pag;
                    $datasource = array_slice($datasource, $this->page_size * $page, $this->page_size);
                    $grid .= self::paging($page, $pag);
                }
                $grid.="\n<input type='hidden' name='" . $this->name . "_id' id='" . $this->name . "_id'/>\n</td>\n</tr>\n</tfoot>";
                //_____________________________genrate body grid______________________________________________________
                $grid .= "\t<tbody>\n";
                foreach ($datasource as $rows)
                {
                    $grid .= "<tr$this->cssclass_TR>\n";
                    //convert class to array
                    if (is_object($rows))
                        $rows = (array )$rows;

                    foreach ($this->columns as $col)
                    {
                        $td_css = '';
                        if ($col->css_class != '')
                            $td_css = ' class="' . $col->css_class . '"';

                        $hide = '';
                        if ($col->hide)
                            $hide = ' style="display:none;"';

                        $fieldname = '';
                        if ($col->template != '')
                        {
                            $maches = self::get_field_list($col);
                            $fieldname = $col->template;
                            foreach ($maches as $field)
                            {
                                $pos = strpos($field, '(');
                                if ($pos != false)
                                {
                                    $func = trim(substr($field, 0, $pos));
                                    $arg = trim(substr($field, $pos + 1, -1));
                                    $fieldname = str_replace("<%$field%>", call_user_func($func, $rows[$arg]), $fieldname);
                                } else
                                    $fieldname = str_replace("<%$field%>", $rows[$field], $fieldname);
                            }
                        } else
                        {
                            $fieldname = $rows[$col->field_name];
                            if ($col->function != '')
                                $fieldname = call_user_func($col->function, $fieldname);
                        }
                        if($col->editable)
                        $grid .= "\t<td data-edit='$col->field_name'$td_css$hide>$fieldname</td>\n";
                        else
                        $grid .= "\t<td $td_css$hide>$fieldname</td>\n";
                    }
                    if ($this->delete->enable)
                        {
                            if($this->delete->cssclass!='')
                            $css=' class="'.$this->delete->cssclass.'"';
                            $grid .= "\t<td><input type='submit' value='".$this->delete->caption."' name='delete'$css></td>\n";
                        }
                    if ($this->update->enable)
                        {
                            if($this->update->cssclass!='')
                            $css=' class="'.$this->update->cssclass.'"';
                            $grid .= "\t<td><input type='submit' value='".$this->update->caption."' name='update'$css></td>\n";
                        }
                        
                    if($this->select->enable)
                        {
                           if($this->select->cssclass!='')
                           $css=' class="'.$this->select->cssclass.'"';
                           $grid .= "\t<td><input type='submit' value='".$this->select->caption."' name='select'$css></td>\n";
                        }
                    $grid .= "</tr>\n";
                }
                //________________________________________________eng entrate body_________________________________________________________
                $grid .= "\t</tbody>\n</table>";
        }
        echo $grid;
    }

    public function command_script($divid)
    {
        $out='';
        if ($this->recivepage == '')
        $this->recivepage = 'window.location.href';
        $out .= "$('#$this->name tbody td').live('dblclick',function(){
            if($(this).data('edit')!=undefined)
            {
            $(this).attr('contenteditable','true');
            $(this).focus();    
            }
        })
        
        $('#$this->name tbody td[data-edit]').live('blur',function(){
           var pid = $(this).closest('tr');
           var id=pid.children('td:eq(0)').text();
           $(this).removeAttr('contenteditable');
           $.post($this->recivepage,{cmd:'update_edit',col:$(this).data('edit'),val:$(this).text(),id:id});
        });
        ";
        if ($this->delete->enable)
        {
            $out .= "$('input[name=delete]').live('click',function(){ 
                     if (confirm('$this->delete_msg')) 
                    {
                        var pid = $(this).closest('tr');
                        var id=pid.children('td:eq(0)').text();
                        $('" . $this->name . "_id').val(id);
                        $.post($this->recivepage,{cmd:'delete',id:id},function(data){
                        $('$this->div').html(data);
                        });
                    }
                    });";
        }

        if ($this->select->enable)
        {
            $out .= "$('input[name=select]').live('click',function(){ 
                      $this->select_jquery   
                      });";
        }
        
        if($this->update->enable)
        {
            $out.="$('input[name=update]').live('click',function(){ 
                        var pid = $(this).closest('tr');
                        var id=pid.children('td:eq(0)').text();
                        $('#" . $this->name . "_id').val(id);
                    $.post($this->recivepage,'cmd=update&'+$('$divid :input').serialize(),function(data){
                    $('$this->div').html(data);
                    });
                    });";
        }

        if ($this->paging)
        {
            $out .= "$('input[name=pageing]').live('click',function(){ 
                        var pid = $(this).data('pnumber');
                        $('#" . $this->name . "_page').val(pid);
                    $.post($this->recivepage,'cmd=paging&'+$('$divid :input').serialize(),function(data){
                    $('$this->div').html(data);
                    });
                    });";
        }
        if($this->select_color!='')
        $out.="
        $('#$this->name tr').hover(function()
        {
            if($(this).parent().is('tbody'))
        $(this).css('background-color','$this->select_color'); 
        },function(){
        $(this).css('background-color','');    
        });";
        return $out;
    }

    function __destruct()
    {
        unset($this->columns);
    }
}

?>